<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax实现搜索联想和自动补全功能</title>
    <style>
        .userInput {
            width: 300px;
            height: 25px;
            font-size: 20px;
            padding-left: 5px;
        }

        .showDataDiv {
            width: 310px;
            border: 1px solid lightgray;
            background-color: antiquewhite;
            display: none;
        }

        .showDataDiv p {
            padding-left: 5px;
            margin-top: 2px;
            margin-bottom: 2px;
        }

        .showDataDiv p:hover {
            cursor: pointer;
            border: 1px blue solid;
            background-color: aliceblue;
        }
    </style>
</head>
<body>
<script type="text/javascript">
    window.onload = () => {
        document.getElementById("keywords").onkeyup = function () {
            if(this.value == ""){
                document.getElementById("datadiv").style.display = "none"
            }else{
                // 发送AJAX请求
                // 1.创建AJAX对象
                var xhr = new XMLHttpRequest();
                // 2.注册回调函数
                xhr.onreadystatechange = () => {
                    if(xhr.readyState == 4){
                        if(xhr.status >= 200 && xhr.status < 300){
                            const json = JSON.parse(xhr.responseText);
                            let html = "";
                            for (let i = 0; i < json.length; i++) {
                                html += "<p onclick='setInput(\""+json[i].content+"\")'>"+json[i].content+"</p>"
                            }
                            document.getElementById("datadiv").innerHTML = html
                            document.getElementById("datadiv").style.display = "block"
                        }

                    }
                }
                // 3.开启通道
                xhr.open("GET", "/ajax/autoComplete?_="+ new Date() .getTime()+"&keywords="+this.value, true);
                // 4.发送请求
                xhr.send();
            }

        }
    }
    function setInput(content){
        document.getElementById("keywords").value = content
        document.getElementById("datadiv").style.display = "none"
    }

</script>

<input type="text" class="userInput" id="keywords">

<div id="datadiv" class="showDataDiv">
<!--    <p>北京疫情最新情况</p>
    <p>北京天气</p>
    <p>北京时间</p>
    <p>北京人</p>-->
</div>
</body>
</html>